package cn.com.czpb.client.module.news.activity;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;

import cn.com.czpb.client.app.MToolBarActivity;
import cn.com.czpb.client.app.MyActivitymanager;
import cn.com.czpb.client.config.CODE;
import cn.com.czpb.client.custorm.smartrefreshalayout.ClassHeader_other;
import cn.com.czpb.client.model.news.NewsBean;
import cn.com.czpb.client.model.news.NewsFlashBean;
import cn.com.czpb.client.model.news.NewsFlashEntity;
import cn.com.czpb.client.model.news.NewsListEntity;
import cn.com.czpb.client.module.news.adapter.NewsItemListViewAdapterNew;
import cn.com.czpb.client.module.news.view.TopDangwuView;
import cn.com.czpb.client.module.news.view.TopViewPagerView;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.ParamUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class DangWuActivity extends MToolBarActivity implements OnRefreshListener, BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener {
    @BindView(R.id.recyclerview_highrise)
    RecyclerView recyclerView;
    @BindView(R.id.swipe_layout)
    SmartRefreshLayout swipe_layout;

//    @BindView(R.id.indicator)
//    CircleIndicator mGuideIndicator;
    private TopViewPagerView topViewPagerView;
    private TopDangwuView topDangwuView;
    private Boolean isFirstLoadFlash = true;
    private NewsItemListViewAdapterNew adapter;
    private List<NewsBean> list;
    private int page = 1;
    private static final int pageSize = 15;//
    private boolean mFlagRefresh = true;//刷新还是加载
    int SCROLL_HIGH;
    @Override
    public void initData() {
        super.initData();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        mImmersionBar
                .statusBarDarkFont(true)
                .init();
    }
    @OnClick(R.id.ll_back)
    public void goBack(View view){
        activity.onBackPressed();
    }
    @Override
    protected int setLayoutId() {
        return R.layout.activity_dang_wu;
    }
    private void init() {
//        initFlash();

        list = new ArrayList<>();


        adapter = new NewsItemListViewAdapterNew(activity,list, false);
        adapter.setOnItemChildClickListener(this);
        adapter.setOnLoadMoreListener(this,recyclerView);
        topDangwuView = TopDangwuView.instance(activity);
        adapter.addHeaderView(topDangwuView.getView(),1);
        GridLayoutManager manager = new GridLayoutManager(activity, 1);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
//        int height = (int) getResources().getDimension(R.dimen.x2);
//        recyclerView.addItemDecoration(new RecycleViewDivider(activity,
//                LinearLayoutManager.HORIZONTAL, height,
//                getResources().getColor(R.color.color_e8e8e8)));
        swipe_layout.setRefreshHeader(new ClassHeader_other(this));

        swipe_layout.setOnRefreshListener(this);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);


            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                LogUtils.e("scroll--" + dx + "--" + dy + "---" + SCROLL_HIGH);
                SCROLL_HIGH-=dy;
            }
        });
        initList();
        getFlash();
    }

    private void initList() {
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("tid", CODE.TID_DAGNWU);
        map.put("Page", page + "");
        map.put("PageSize", pageSize + "");
        map.put("device", DeviceUtils.getMyUUID(activity));
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
            LogUtils.i("uid-->" + spu.getUser().getUid());
        }
        Factory.provideHttpService().newslist(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsListEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsListEntity entity) {
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsListEntity>() {
                    @Override
                    public void call(NewsListEntity entity) {
                        LogUtils.e("code--" + entity.code);
                        if (mFlagRefresh) {
                            swipe_layout.finishRefresh();
                        }
                        if ("200".equals(entity.code)) {
                            LogUtils.e("code--" + entity.msg);
                            setListData(entity.data);
                            adapter.notifyDataSetChanged();
                            LogUtils.e(list.size() + "");
                        } else if ("209".equals(entity.code)) {

                            list.clear();
                            adapter.notifyDataSetChanged();
                        } else {
                            if (!mFlagRefresh) {
                                page--;
                            }
                        }
                        mFlagRefresh = false;
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("throwable--" + throwable.getMessage());
                    }
                });


    }

    public void setListData(List<NewsBean> list) {
        if (mFlagRefresh) {
            adapter.setNewData(list);
            adapter.notifyDataSetChanged();
        } else {
            adapter.addData(list);
            adapter.notifyDataSetChanged();
            adapter.loadMoreComplete();
        }
        LogUtils.i("size-->" + adapter.getData().size());
        if (list.size() < pageSize) {
            //关闭刷新
            adapter.loadMoreEnd(true);
        }
    }
    //    获取幻灯
    private void getFlash() {
        LogUtils.i("init", "getflash");
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("tid", CODE.TID_DAGNWU);
        Factory.provideHttpService()
                .newsFlashlist(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsFlashEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsFlashEntity entity) {
                        LogUtils.i("flash--200-->" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsFlashEntity>() {
                               @Override
                               public void call(NewsFlashEntity entity) {




                                       if (isFirstLoadFlash) {
                                           LogUtils.i("flash--200-->成功-first");
                                           isFirstLoadFlash = false;
                                           setFlashData(entity.data.flash);
                                       } else {
                                           topViewPagerView.reFreshFlashData(entity.data.flash);
                                       }
                               }
                           }, new Action1<Throwable>() {
                               @Override
                               public void call(Throwable throwable) {

                                   LogUtils.i("flash--200-->失败" + throwable.toString());
                               }
                           }
                );
    }

    private void setFlashData(List<NewsFlashBean> mViewPagelist) {
            topViewPagerView = TopViewPagerView.Instance(activity);
            adapter.addHeaderView(topViewPagerView.getView(),0);
            topViewPagerView.reFreshFlashData(mViewPagelist);
    }
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        page = 1;
        mFlagRefresh = true;
        swipe_layout.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipe_layout.finishRefresh();
                getFlash();
            }
        },3000);

        initList();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        final NewsBean newsBean = (NewsBean) adapter.getItem(position);
        switch (view.getId()) {
            case R.id.newsItem_root:
                ////REFACTOR: 2017/8/18 添加浏览量bug
//                addCount(newsBean);
                MyActivitymanager.pushActivity(activity, newsBean, newsBean.getTid(), "newsitem", newsBean.getRvalue());
                LogUtils.e("rtype--" + newsBean.getRtype());
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onLoadMoreRequested() {
        mFlagRefresh = false;
        page++;
        initList();
    }
}
